﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Web;
using System.Windows.Forms;
using RichTextBoxCtrl;
using OpenSoftStore.BusinessLogic.Common;
using OpenSoftStore.BusinessLogic.Member;
using OpenSoftStore.Client.BLL;
using OpenSoftStore.Client.UIL.ManageMember.Info;
using OpenSoftStore.Orm;
using OpenSoftStore.Orm.Model;
using OpenSoftStore.Client.Common;

namespace OpenSoftStore.Client.UIL.ManageMember
{
    public partial class MemberList : UserControl
    {
        private static MemberList instance;
        public MemberLogic LgcMember;
        public T_Member TblMember;
        public TreeLogic LgcTree;
        public T_Dinner Tdinner;
        public DinnerLogic LgcDinner;

        /// <summary>
        /// 返回一个该控件的实例。如果之前该控件已经被创建，直接返回已创建的控件。
        /// 此处采用单键模式对控件实例进行缓存，避免因界面切换重复创建和销毁对象。
        /// </summary>
        public static MemberList Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new MemberList();
                }
                //BindDataGrid(); // 每次返回该控件的实例前，都将对DataGridView控件的数据源进行重新绑定。
                return instance;
            }
        }

        /// <summary>
        /// 私有的控件实例化方法，创建实例只能通过该控件的Instance属性实现。
        /// </summary>
        public MemberList()
        {
            InitializeComponent();
            SPACommon.SetUiStyle(this);
            DgvGrid.AutoGenerateColumns = false;
            dgvPreorder.AutoGenerateColumns = false;
            this.Dock = DockStyle.Fill;

            LgcMember = new MemberLogic();
            TblMember = new T_Member();
            LgcTree = new TreeLogic();

            LgcDinner = new DinnerLogic();
            Tdinner = new T_Dinner();
            SetUi();

            btnSearch_Click(null, null);
            SPACommon.SetDataGridStyle(DgvGrid);
            SPACommon.ShowSummary(DgvGrid);
            SPACommon.SetDataGridStyle(dgvGridDinner);
            SPACommon.SetDataGridStyle(dgvPreorder);

            var dinners=new List<T_Dinner>();
            dinners.Add(new T_Dinner { Name = "全部", Id = "" });
            dinners.AddRange(LgcDinner.GetDinners());
            cmbDinner.DataSource = dinners;
            cmbDinner.DisplayMember = "Name";
            cmbDinner.ValueMember = "Id";
            cmbState.SelectedIndex = 0;

            dtpTo.Value = DateTime.Now.AddDays(1);

            cmbDinnerState.SelectedIndex = 0;
            cmbLogic.SelectedIndex = 0;


            tlMemberAdd.Visible = SysPowerManager.IsHavePower(SysPowerManager.添加客户);
            tlMemberUpdate.Visible = SysPowerManager.IsHavePower(SysPowerManager.查看客户详细);
            tlMemberDelete.Visible = SysPowerManager.IsHavePower(SysPowerManager.删除客户);
            tlDinner.Visible = SysPowerManager.IsHavePower(SysPowerManager.办理套餐);
            tsbMemberValueRecord.Visible = SysPowerManager.IsHavePower(SysPowerManager.充值);
            tslReturnMoney.Visible = SysPowerManager.IsHavePower(SysPowerManager.还款);
            tlState.Visible = SysPowerManager.IsHavePower(SysPowerManager.挂失_恢复);
			//	bool flag = SysPowerManager.IsHavePower(SysPowerManager.添加客户提醒);
            btnTree_Add.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理客户分类);
            btnTree_Update.Visible= SysPowerManager.IsHavePower(SysPowerManager.管理客户分类);
            btnTree_Delete.Visible = SysPowerManager.IsHavePower(SysPowerManager.管理客户分类);
        }

        private void SetUi()
        {
            trTree.Refresh();
            LgcTree.SetTreeNode(LgcTree.GetMemberTrees(), trTree);
            trTree.ExpandAll();
            trTree.SelectedNode = trTree.Nodes[0];
            SPACommon.SetTreeStyle(trTree);
            trTreeDinner.Refresh();
            LgcTree.SetTreeNode(LgcTree.GetDinnerTrees(), trTreeDinner);
            trTreeDinner.ExpandAll();
            trTreeDinner.SelectedNode = trTreeDinner.Nodes[0];
            SPACommon.SetTreeStyle(trTreeDinner);
            dgvGridDinner.AutoGenerateColumns = false;

            LgcTree.SetTreeNode(LgcTree.GetRemindTree(), tvRemind);
            tvRemind.ExpandAll();
            tvRemind.SelectedNode = tvRemind.Nodes[0];
            SPACommon.SetTreeStyle(tvRemind);
        }

        public void RefreshTree()
        {
            trTree.Nodes.Clear();
            trTree.Refresh();
            LgcTree.SetTreeNode(LgcTree.GetMemberTrees(), trTree);
            trTree.ExpandAll();
            trTree.SelectedNode = trTree.Nodes[0];
            SPACommon.SetTreeStyle(trTree);
        }

        private void Lbl_Department_Click(object sender, EventArgs e)
        {

        }

        private void DrpDepartment_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {
        }

        private void toolStripLabel1_Click(object sender, EventArgs e)
        {
            var memberAddWindow = new MemberAddWindow();
            memberAddWindow.UcMemberList = this;
            memberAddWindow.ShowDialog();
        }

        private void toolStripLabel3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除吗？", "提示",
                MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return;
            if (DgvGrid.CurrentRow == null) return;
            var id = DgvGrid.CurrentRow.Cells["ColMemberId"].Value.ToString();
            var name = DgvGrid.CurrentRow.Cells["ColMemberName"].Value.ToString();
            TblMember.Id = id;
            string message = "删除失败。";
            if (name == "临时客户")
            {
                message = string.Format("[{0}]是系统数据，不能删除！", name);
                FormSysMessage.ShowSuccessMsg(message);
                return;
            }
            if (LgcMember.Delete(TblMember) == 0) FormSysMessage.ShowSuccessMsg(message); ;
            btnSearch_Click(null, null);
        }

        public void btnSearch_Click(object sender, EventArgs e)
        {
            var name = txt_name.Text;
            var dinner = "";
            if(cmbDinner.SelectedValue!=null)
                dinner = cmbDinner.SelectedValue.ToString();
            var state = cmbState.Text;
            if (state == "全部") state = "";
            var chkHave = chkHaveValue.Checked;
            var haveValue = nudHaveValue.Value;
            var chkOwed = chkOwedMoney.Checked;
            var owedMoney = nudOwedMoney.Value;
            var document = txtDocument.Text;
            string whereDinner = "";
            if (!string.IsNullOrEmpty(dinner))
                whereDinner =
                    "and (select Count(*) from T_DinnerSale where T_DinnerSale.MemberId = T_Member.Id and T_DinnerSale.DinnerId like '%{2}%') >0 ";
            string where =
               string.Format(" where (T_Member.Name like '%{0}%' or T_Member.CardId like '%{0}%' or T_Member.TelNum like '%{0}%') and T_Member.State like '%{1}%' " +
                             whereDinner,
               name, state, dinner);
            if (chkHave)
            {
                where = where + string.Format("and T_Member.HaveValue <= {0} ", haveValue);
            }
            if (chkOwed)
            {
                where = where + string.Format("and T_Member.OwedMoney >= {0} ", owedMoney);
            }
            if (trTree.SelectedNode.Tag != null)
            {
                where = where + string.Format("and T_Tree.Code like '{0}%' ", trTree.SelectedNode.Tag.ToString());
            }
            if (!string.IsNullOrEmpty(document))
            {
                document = HttpUtility.UrlEncode(document, Encoding.GetEncoding("GB2312")).Replace("%", "\\'");
                document = HttpUtility.UrlEncode(document, Encoding.UTF8).Replace("%", "|");
                where = where + string.Format("and (T_Member.Document Like '%{0}%' or T_Member.DocumentSolution Like '%{0}%')", document);
            }
            DgvGrid.DataSource = null;
            DgvGrid.DataSource = LgcMember.GetMemberDataTable(where);
            lblMemberCount.Text = DgvGrid.RowCount.ToString();
        }

        private void toolStripLabel2_Click(object sender, EventArgs e)
        {
            if (DgvGrid.CurrentRow == null) return;
            //var window = new MemberAddWindow();
            var id = DgvGrid.CurrentRow.Cells["ColMemberId"].Value.ToString();
            var name = DgvGrid.CurrentRow.Cells["ColMemberName"].Value.ToString();
            var cardId = DgvGrid.CurrentRow.Cells["ColMemberCardId"].Value.ToString();
            var member = new T_Member { Id = id, Name = name, CardId = cardId };
            var window = new MemberInfoEditWindow();
            window.SetMember(member);
            window.ShowDialog();

        }

        private void trTree_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.SelectedNode.EndEdit(true);
            if (!LgcTree.SaveTreeNode(trTree, sender, e, "MemberTree"))
                FormSysMessage.ShowSuccessMsg("保存失败！");
        }

        private void btnTree_AddClick(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;

            MemberTreeDinnerAddWindow memberTreeDinnerAddWindow = new MemberTreeDinnerAddWindow();
            string parentId = trTree.SelectedNode.Name;
            memberTreeDinnerAddWindow.SetTree(new T_Tree { ParentId = parentId });
            memberTreeDinnerAddWindow.ShowDialog();
            //var treeNode = new TreeNode { Text = "新子项" };
            //TreeNode tnParent = trTree.SelectedNode;
            //tnParent.Nodes.Add(treeNode);
            //trTree.SelectedNode = treeNode;
            //treeNode.BeginEdit();
        }

        private void btnTree_Update_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null) return;
            trTree.LabelEdit = true;
            TreeNode treeNode = trTree.SelectedNode;
            var tree = new T_Tree { Id = treeNode.Name };
            MemberTreeDinnerAddWindow memberTreeDinnerAdd = new MemberTreeDinnerAddWindow();
            memberTreeDinnerAdd.GetData(tree.Id);
            memberTreeDinnerAdd.ShowDialog();
            //trTree.SelectedNode.BeginEdit();
        }

        private void btnTree_Delete_Click(object sender, EventArgs e)
        {
            if (trTree.SelectedNode == null)
            {
                return;
            }
            string treeCode = trTree.SelectedNode.Tag.ToString();
            var dataTable = LgcMember.GetMemberView(" where T_Tree.Code like '" + treeCode + "%'");
            if (dataTable == null || dataTable.Count == 0)
            {
                List<T_MemberTree> list = LgcMember.GetMemberTreeView(" where T_Tree.Code like '" + treeCode + "%'").ToList();
                LgcMember.DeleteMemberTree(list);
                LgcTree.Delete(trTree);
            }
            else
            {
                FormSysMessage.ShowMessage("该节点下仍有数据，不能删除！");
            }
        }

        private void label6_Click(object sender, EventArgs e)
        {

        }

        public void btnSearchDinner_Click(object sender, EventArgs e)
        {
            if (trTreeDinner.SelectedNode == null ) return;
            if (trTreeDinner.SelectedNode.Tag == null) trTreeDinner.SelectedNode.Tag = "";
            string code = trTreeDinner.SelectedNode.Tag.ToString();
            var state = cmbDinnerState.Text == "全部" ? "" : cmbDinnerState.Text;
            string where = string.Format(" where T.Code like '{0}%' and (D.Name like '%{1}%' or D.Remark like '%{1}%') and D.State like '%{2}%'", code, txtName.Text, state);
            if (chkPrice.Checked) where = where + string.Format(" and Price {0} {1}", cmbLogic.Text, numPrice.Value);
            dgvGridDinner.DataSource = null;
            dgvGridDinner.DataSource = LgcDinner.GetDinnerView(where);
            lblDinnerCount.Text = dgvGridDinner.RowCount.ToString();
        }

        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            var dinnerEditWindow = new DinnerEditWindow();
            //dinnerEditWindow.UcMemberList = this;
            dinnerEditWindow.ShowDialog();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            if (dgvGridDinner.CurrentRow == null) return;
            var window = new DinnerEditWindow();
            var id = dgvGridDinner.CurrentRow.Cells["DinnerId"].Value.ToString();
            //window.UcMemberList = this;
            window.GetDinner(id);
            window.Show();
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("确定要删除吗？", "提示",
             MessageBoxButtons.OKCancel, MessageBoxIcon.Information) != DialogResult.OK) return;
            if (dgvGridDinner.CurrentRow == null) return;
            var id = dgvGridDinner.CurrentRow.Cells["DinnerId"].Value.ToString();
            Tdinner.Id = id;
            string message = "删除成功。";
            if (LgcDinner.Delete(Tdinner) == 0) message = "删除失败。";
            FormSysMessage.ShowSuccessMsg(message);
            btnSearch_Click(null, null);
        }

        private void toolStripLabel6_Click(object sender, EventArgs e)
        {
            if (DgvGrid.CurrentRow == null) return;
            var window = new MemberAddWindow();
            var id = DgvGrid.CurrentRow.Cells["ColMemberId"].Value.ToString();
            var dinnerSalePayWindow = new DinnerSalePayWindow();
            dinnerSalePayWindow.SetMember(id);
            dinnerSalePayWindow.ShowDialog();
        }

        private void tsbMemberValueRecord_Click(object sender, EventArgs e)
        {
            if (DgvGrid.CurrentRow == null) return;
            var window = new MemberAddWindow();
            var id = DgvGrid.CurrentRow.Cells["ColMemberId"].Value.ToString();
            var cardId = DgvGrid.CurrentRow.Cells["ColMemberCardId"].Value.ToString();
            var name = DgvGrid.CurrentRow.Cells["ColMemberName"].Value.ToString();
            //var treeName = DgvGrid.CurrentRow.Cells["TreeName"].Value.ToString();
            TblMember=new T_Member();
            TblMember.Id = id;
            TblMember.CardId = cardId;
            TblMember.Name = name;
            var memberValueRecordEditWindow = new MemberValueRecordEditWindow();
            memberValueRecordEditWindow.GetMember(TblMember);
            memberValueRecordEditWindow.ShowDialog();
        }

        private void MemberList_Load(object sender, EventArgs e)
        {

        }

        private void tslReturnMoney_Click(object sender, EventArgs e)
        {
            if (DgvGrid.CurrentRow == null) return;
            var id = DgvGrid.CurrentRow.Cells["ColMemberId"].Value.ToString();
            var cardId = DgvGrid.CurrentRow.Cells["ColMemberCardId"].Value.ToString();
            var name = DgvGrid.CurrentRow.Cells["ColMemberName"].Value.ToString();
            TblMember=new T_Member();
            TblMember.Id = id;
            TblMember.CardId = cardId;
            TblMember.Name = name;

            var memberReturnMoneyEditWindow = new MemberReturnMoneyEditWindow();
            memberReturnMoneyEditWindow.SetMember(TblMember);
            memberReturnMoneyEditWindow.ShowDialog();
        }

        private void trTree_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (trTree.SelectedNode.Tag == null) return;
            //DgvGrid.DataSource = null;
            //string sql = "where T_Tree.Code like '" + trTree.SelectedNode.Tag.ToString() +
            //             "%' Order By T_Member.AddTime desc";
            //DgvGrid.DataSource = LgcMember.GetMemberView(sql);
            btnSearch_Click(null, null);
            lblMemberCount.Text = DgvGrid.RowCount.ToString();
        }

        private void btnTree_DinnerAdd_Click(object sender, EventArgs e)
        {
            if (trTreeDinner.SelectedNode == null) return;
            trTreeDinner.LabelEdit = true;
            var treeNode = new TreeNode { Text = "新子项" };
            TreeNode tnParent = trTreeDinner.SelectedNode;
            tnParent.Nodes.Add(treeNode);
            trTreeDinner.SelectedNode = treeNode;
            treeNode.BeginEdit();
            dgvGridDinner.DataSource = null;
        }

        private void btnTree_DinnerUpdate_Click(object sender, EventArgs e)
        {
            if (trTreeDinner.SelectedNode == null) return;
            trTreeDinner.LabelEdit = true;
            trTreeDinner.SelectedNode.BeginEdit();
        }

        private void btnTree_DinnerDelete_Click(object sender, EventArgs e)
        {
            LgcTree.Delete(trTreeDinner);
            trTreeDinner.Select();
        }

        private void trTreeDinner_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (trTreeDinner.SelectedNode == null) return;
            trTreeDinner.SelectedNode.EndEdit(true);
            LgcTree.SaveTreeNode(trTreeDinner, sender, e, "DinnerTree");
          
        }

        private void trTreeDinner_AfterSelect(object sender, TreeViewEventArgs e)
        {
            btnSearchDinner_Click(null, null);
        }

        private void toolStripLabel9_Click(object sender, EventArgs e)
        {
            if (DgvGrid.CurrentRow == null) return;
            var id = DgvGrid.CurrentRow.Cells["ColMemberId"].Value.ToString();
            TblMember.Id = id;
            var member = LgcMember.Where<T_Member>(m => m.Id == TblMember.Id).ToList()[0];
            member.State = member.State == "正常" ? "已挂失" : "正常";
            LgcMember.Update(member);
            btnSearch_Click(null, null);
        }

        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            SPACommon.ExportToExcel(DgvGrid);
        }

        private void toolStripButton9_Click_1(object sender, EventArgs e)
        {
            SPACommon.ExportToExcel(DgvGrid, "客户");
        }

        private void tsbAdd_Click(object sender, EventArgs e)
        {

        }

        private void toolStripLabel5_Click(object sender, EventArgs e)
        {
            if (DgvGrid.SelectedRows.Count != 0)
            {
                string memberId = DgvGrid.SelectedRows[0].Cells["ColMemberId"].Value.ToString();
                PreorderAddWindow preorderAddWindow = new PreorderAddWindow(memberId);
                preorderAddWindow.ShowDialog();
            }

        }

        public void btnQuery_Click(object sender, EventArgs e)
        {
            var from = dtpFrom.Value.ToShortDateString();
            var to = dtpTo.Value.ToShortDateString();
            string queryStr = txtQuery.Text;

            string whereStr = string.Format(" where P.AddTime between #{0}# and #{1}# and (M.CardId like '{2}%' or M.Name like '{2}%' or M.TelNum like '{2}%' or A.Name like '{2}%')", from, to, queryStr);
            dgvPreorder.DataSource = LgcMember.GetPreorderTable(whereStr);
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            var from = dtpFrom.Value.ToShortDateString();
            var to = dtpTo.Value.ToShortDateString();
            if (tabControl1.SelectedTab.Name == "tpPreorder")
            {
                string whereStr = string.Format(" where P.AddTime between #{0}# and #{1}#", from, to);
                dgvPreorder.DataSource = LgcMember.GetPreorderTable(whereStr);
            }
            else if (tabControl1.SelectedTab.Name == "tpRemind")
            {
                remindList1.LoadControlData();
            }
        }

        private void tsbUpdate_Click(object sender, EventArgs e)
        {
            if (dgvPreorder.SelectedRows.Count == 0)
            {
                FormSysMessage.ShowMessage("请选择一行修改！");
                return;
            }

            PreorderAddWindow preorderAddWindow = new PreorderAddWindow(null);
            preorderAddWindow.GetPreorder(dgvPreorder.SelectedRows[0].Cells["Id"].Value.ToString());
            preorderAddWindow.ShowDialog();
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvPreorder.SelectedRows.Count == 0)
            {
                FormSysMessage.ShowMessage("请选择一行删除！");
                return;
            }

            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                string id = dgvPreorder.SelectedRows[0].Cells["Id"].Value.ToString();
                LgcMember.Delete(new T_Preorder { Id = id });

                btnQuery_Click(null, null);
            }
        }

        private void toolStripLabel4_Click(object sender, EventArgs e)
        {
            if (DgvGrid.SelectedRows.Count == 0) return;

            string id = DgvGrid.SelectedRows[0].Cells["ColMemberId"].Value.ToString();
            RemindAddWindow remindAddWindow = new RemindAddWindow(id);
            remindAddWindow.ShowDialog();
        }

        private void tpRemind_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton5_Click(object sender, EventArgs e)
        {

        }

        private void toolStripButton4_Click(object sender, EventArgs e)
        {
            if (remindList1.dgvRemind.SelectedRows.Count == 0)
            {
                FormSysMessage.ShowMessage("请选择一行删除！");
                return;
            }

            if (MessageBox.Show("确定要删除吗？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information) == DialogResult.OK)
            {
                string id = remindList1.dgvRemind.SelectedRows[0].Cells["Id"].Value.ToString();
                LgcMember.Delete(new T_Remind { Id = id });
                remindList1.btnSearch_Click(null, null);
            }

        }

        private void tvRemind_AfterSelect(object sender, TreeViewEventArgs e)
        {

            if (tvRemind.SelectedNode.Tag == null) return;


            remindList1.GetRemindList(" where T.Code like '" + tvRemind.SelectedNode.Tag.ToString() + "%'");
        }

        private void tvRemind_AfterLabelEdit(object sender, NodeLabelEditEventArgs e)
        {
            if (tvRemind.SelectedNode == null) return;
            tvRemind.SelectedNode.EndEdit(true);
            LgcTree.SaveTreeNode(tvRemind, sender, e, "RemindTree");
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            if (tvRemind.SelectedNode == null) return;
            TreeNode tnParent = tvRemind.SelectedNode;
            tvRemind.LabelEdit = true;
            var treeNode = new TreeNode { Text = "新子项" };

            tnParent.Nodes.Add(treeNode);
            tvRemind.SelectedNode = treeNode;
            treeNode.BeginEdit();
        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            if (tvRemind.SelectedNode == null) return;
            tvRemind.LabelEdit = true;
            tvRemind.SelectedNode.BeginEdit();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            LgcTree.Delete(tvRemind);
        }

        private void btnSearch_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                btnSearch_Click(null, null);
            }
        }

        private void tlInputWordToAdd_Click(object sender, EventArgs e)
        {
            var memberAddWindow = new MemberAddWindow();
            memberAddWindow.UcMemberList = this;
            memberAddWindow.Show();
            memberAddWindow.memberAdd.InputWord();

        }

        private void DgvGrid_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            toolStripLabel2_Click(null, null);
        }

        private void dgvGridDinner_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex == -1) return;
            toolStripButton2_Click(null, null);
        }

        private void txt_name_KeyUp(object sender, KeyEventArgs e)
        {
            btnSearch_Click(null, null);
        }

        private void txtDocument_KeyUp(object sender, KeyEventArgs e)
        {
            btnSearch_Click(null, null);
        }

    }
}
